# 常量：开始
# 常量：版权
__author__: str = "寒冬利刃"
__version__: str = "2.0.0"
__copyright__: str = "Copyright © 2025 寒冬利刃."

# 常量：程序
program_name: str = "寒冬消息轰炸机"
program_name_in_English: str = "HDmsgbomber"

# 常量：依赖
import os
import sys
import winshell
import jinja2
import webview
import ctypes
import json
import atexit

# 常量：路径
if getattr(sys, "frozen", False):
    base_dir: str = os.path.dirname(sys.executable)
elif __file__:
    base_dir: str = os.path.dirname(__file__)
os.chdir(base_dir)
desktop: str = winshell.desktop()
appdata: str = winshell.application_data()

# 常量：错误文件
if not os.path.isfile(os.path.abspath(f"{base_dir}\\ERROR")):
    with open(f"{base_dir}\\ERROR", "w", encoding = "utf-8"):
        pass
error_file = open(f"{base_dir}\\ERROR", "a", encoding = "utf-8")
@atexit.register
def end_error_file() -> None:
    error_file.close()
def write_error(error: any) -> None:
    error_file.write(str(error))

# 常量：设置
if not os.path.isdir(os.path.abspath(f"{appdata}\\{program_name_in_English}")):
    os.makedirs(f"{appdata}\\{program_name_in_English}", exist_ok = True)

if os.path.isfile(os.path.abspath(f"{appdata}\\{program_name_in_English}\\setting.json")):
    with open(f"{appdata}\\{program_name_in_English}\\setting.json", "r", encoding = "utf-8") as file:
        setting: dict = json.load(file)
elif os.path.isfile(os.path.abspath(f"{base_dir}\\setting.json")):
    with open(f"{base_dir}\\setting.json", "r", encoding = "utf-8") as file:
        setting: dict = json.load(file)
else:
    write_error("未找到默认的设置文件，请重新安装软件！\n")
    exit()

# 常量：界面
loader: jinja2.FileSystemLoader = jinja2.FileSystemLoader(f"{base_dir}\\ui")
env: jinja2.Environment = jinja2.Environment(loader = loader)
env.globals["base_dir"] = base_dir
env.globals["static"] = f"{base_dir}\\static"
env.globals["author"] = __author__
env.globals["version"] = __version__
env.globals["copyright"] = __copyright__
env.globals["program_name"] = program_name
env.globals["program_name_in_English"] = program_name_in_English
#常量：结束

# 程序：开始
# 程序：管理员权限：开始
def isAdmin() -> None:
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def admin() -> None:
    if os.path.isfile(os.path.abspath(f"{base_dir}\\{program_name_in_English}.exe")):
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, f"{base_dir}\\{program_name_in_English}.exe", None, 1)
    elif os.path.isfile(os.path.abspath(f"{base_dir}\\main.py")):
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, f"{base_dir}\\main.py", None, 1)
# 程序：管理员权限：结束

root = webview.Window("", "", "") # 古老特性：带注释的变量不能全局化

# 程序：js_api：开始
class Api():
    global root
    def min(self) -> None:
        root.minimize()
    def quit(self) -> None:
        root.destroy()
# 程序：js_api：结束

# 程序：主函数：开始
def main() -> None:
    global root
    debug: bool = os.path.isfile(os.path.abspath(f"{base_dir}\\DEBUG"))
    html: str = env.get_template("index.html").render()
    with open(f"{base_dir}\\index.html", "w", encoding = "utf-8") as file:
        file.write(html)
    api: Api = Api()
    root = webview.create_window(
        url = f"{base_dir}/index.html",
        title = "寒冬消息轰炸机",
        frameless = True,
        easy_drag = True,
        js_api = api,
    )
    webview.start(debug = debug)
# 程序：主函数：结束
# 程序：结束

# 运行：开始
if __name__ == "__main__":
    if isAdmin():
        try:
            main()
        except Exception as error:
            write_error(error)
    else:
        admin()
# 运行：结束